using UnityEngine;
using System.Collections;


// to use the script use the following line
//GetComponent<FlattenVertexCircle>().flattenVertexes(hit.point, 3);

public class FlattenVertexCircle : MonoBehaviour {
	
	private GameObject theGround;
	private Mesh groundMesh;
		
		
	// Use this for initialization
	void Start () {
		getNewGroundDetails();
	}
	
	void getNewGroundDetails(){
		theGround = GameObject.Find("GroundMesh_1");
	}
	
	public Vector3 flattenVertexes(Vector3 point, float distance){
		
		groundMesh = theGround.GetComponent<MeshFilter>().mesh;
		
		Vector3 localTurretPosition = transform.InverseTransformPoint(point);
		
		Vector3[] vertices = groundMesh.vertices;
		ArrayList verticesToChange = new ArrayList();
		float totalValue = 0;
		
		for(int i = 0; i < vertices.Length; i++){
			if(Vector3.Distance(vertices[i], localTurretPosition) < distance){
				verticesToChange.Add(i);
				
				totalValue += vertices[i].y;
			}
		}
		
		float newHightValue = totalValue/verticesToChange.Count;
		
		for(int p = 0; p < verticesToChange.Count; p++){
			vertices[(int)verticesToChange[p]].y = newHightValue;
		}
		localTurretPosition.y = newHightValue;
		Vector3 globalGroundLevel = transform.TransformPoint(localTurretPosition);
		
		groundMesh.vertices = vertices;
		groundMesh.RecalculateNormals();
		
		return globalGroundLevel;
	}
	
	
	// Update is called once per frame
	void Update () {
	
	}
}
